!!! requirements.txt !!!

torch==1.4.0 
matplotlib==3.4.2
numpy==1.21.1
scipy==1.7.0
pygame==1.9.6
tensorboard==2.5.0
opencv-python==4.5.3.56


!!! wheel_config.ini !!!

[G29 Racing Wheel]
steering_wheel = 0
throttle = 2
brake = 1
reverse = 5
handbrake = 4


!!! utils.py !!!

import sys
import pygame
def signal_handler(sig, frame):
    print('Procedure terminated!')
    pygame.display.quit()
    pygame.quit()
    sys.exit(0)

from scipy.interpolate import interp1d

## This function provides a prospective lateral-coordinate generator w.r.t possible longitudinal coordinates
## for the ego vehicle in Scenario 0, which can be taken as a demonstration 
def get_path():
    waypoint_x_mark = np.array([200,212.5,225,237.5,250,300])
    waypoint_y_mark = np.array([335,336.5,338,337.5,335,334])
    pathgenerator = interp1d(waypoint_x_mark, waypoint_y_mark,kind='cubic')
    return pathgenerator



import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np

def weights_init_normal(m):
    '''Takes in a module and initializes all linear layers with weight
       values taken from a normal distribution.'''

    classname = m.__class__.__name__
    # for every Linear layer in a model
    if classname.find('Linear') != -1:
        y = m.in_features
    # m.weight.data shoud be taken from a normal distribution
        m.weight.data.normal_(0.0,1/np.sqrt(y))
    # m.bias.data should be 0
        m.bias.data.fill_(0)


class NET(nn.Module):
    def __init__(self):
        super(NET, self).__init__()
        self.relu = nn.ReLU()
        self.conv1 = nn.Conv2d(1,6,6)
        self.conv2 = nn.Conv2d(6,16,6)
        self.fc = nn.Linear(16*7*16, 128)
    
    def forward(self, x):
        x = x.unsqueeze(1)

        x = F.max_pool2d( self.conv1(x),2)
        x = F.max_pool2d( self.conv2(x),2)
        x = x.view(x.size(0),16*16*7)
        
        x = self.fc(x)
        x = self.relu(x)
        
        return x
        
        
class RND(nn.Module):
    def __init__(self, use_cuda = True):
        super(RND, self).__init__()
        
        self.use_cuda = use_cuda
        self.fix = NET()
        self.estimator = NET()
        
        self.fix.apply(weights_init_normal)
        
        self.estimator.apply(weights_init_normal)
        
        self.criterion = nn.MSELoss()
        self.optim = optim.Adam(self.estimator.parameters(),0.0001)
        
        if self.use_cuda:
            self.fix.cuda()
            self.estimator.cuda()
        
    def forward(self, state):
        
        state = torch.tensor(state, dtype=torch.float).reshape(1,45,80)
        if self.use_cuda:
            state = state.cuda()
        
        target = self.fix.forward(state)
        estimate = self.estimator.forward(state)
        
        loss = self.criterion(estimate, target)
        self.optim.zero_grad()
        
        loss.backward()
        self.optim.step()
        
        error = loss.item()
        mu = torch.mean(target)
        std = torch.std(target)
        
        return error, mu.detach().cpu().numpy(), std.detach().cpu().numpy()
    
    def get_reward_i(self, state):
        
        error, mu, std = self.forward(state)
        
        alpha = 1+(error-mu)/std
        
        x = min( max(alpha, 1), 2)
        
        return x


!!! train_offline.py !!!

import numpy as np
import matplotlib.pyplot as plt
import time
import scipy.io as scio
import os
import pygame
import signal

import torch
from torch.utils.tensorboard import SummaryWriter   
writer = SummaryWriter('./TD3_based_DRL/checkpoints/log')

seed = 2
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

# import CARLA environment
from env import scenario
env = scenario()

from utils import signal_handler, get_path, RND
rnd = RND()

# arguments
MAX_EPISODES = 1500 
MAX_STEPS = 5e4
LOAD = 0
PID = 0
REWARD_SHAPING = 1
PRE_EXPLORATION = 1
PRE_INIT_CRITIC = 0

# construct the DRL agent
device = torch.device('cuda') if torch.cuda.is_available() else ('cpu')
algorithm = 0

from TD3_based_DRL.priority_replay import Memory
if algorithm == 0:
    from TD3_based_DRL.TD3HUG import DRL
    log_dir = 'TD3_based_DRL/checkpoints/TD3jingda.pth'
elif algorithm == 1:
    from TD3_based_DRL.TD3IARL import DRL
    log_dir = 'TD3_based_DRL/checkpoints/TD3IARL.pth'
elif algorithm == 2:
    from TD3_based_DRL.TD3HIRL import DRL   
    log_dir = 'TD3_based_DRL/checkpoints/TD3HIRL.pth'
else:
    from TD3_based_DRL.TD3 import DRL    
    log_dir = 'TD3_based_DRL/checkpoints/TD3.pth'

s_dim = [env.observation_size_width, env.observation_size_height]
a_dim = env.action_size
DRL = DRL(a_dim, s_dim)

if PRE_INIT_CRITIC:
     DRL.memory_load()
     for _ in range(10000):
         DRL.pre_init_critic()

start_epoch = 0
if os.path.exists(log_dir) and LOAD:
    checkpoint = torch.load(log_dir)
    DRL.load(log_dir)
    start_epoch = checkpoint['epoch'] + 1

var = 0.5  # initial exploration rate


# initialize measurable variables
total_step = 0
a_loss,c_loss = 0,0

loss_critic, loss_actor = [], []

episode_reward_list, global_reward_list, episode_duration_list = [], [], []

previous_action = [[] for i in range(MAX_EPISODES)]
final_action = [[] for i in range(MAX_EPISODES)]

# reward_i: virtual reward (added shaping term); reward_e: real reward
reward_i_record = [[] for i in range(MAX_EPISODES)]
reward_e_record = [[] for i in range(MAX_EPISODES)]

# calculate human intervention rate
action_disturbing_degree = []
intervene_percent_per_episode = [[] for i in range(MAX_EPISODES)]
intervene_percent = []

# record the x,y coordinates of the ego vehicle
x_per_episode = [[] for i in range(MAX_EPISODES)]
y_per_episode = [[] for i in range(MAX_EPISODES)]

# record the q value difference
qlist = []

path_generator = get_path()

env = scenario(random_spawn = False)

start_time = time.perf_counter()

for i in range(start_epoch, MAX_EPISODES):
    reward = 0
    ep_reward = 0      
    step = 0
    step_intervene = 0

    done = False

    list_fdbk = []
    list_fdbk.append(None)
    
    flag_qrecord = 0

    pid_guide = False
    pid_seed = np.random.randint(0,3)
    pid_intergal = 0

    if i == start_epoch:
        env.destroy()

    env = scenario(random_spawn = False)
    State, scope = env.obtain_observation()

    while True:
        ## Section DRL's actting ##
        action = DRL.choose_action(State)
        # add a Gaussian noise to the DRL action
        action = np.clip( np.random.normal(action, var), -1, 1)

        previous_action[i].append(action)
        ## End of Section DRL's actting
    

        ## Section PI controller (can sometimes substitute real human participants) ##
        # calculate some indicators of the environment to determine the activation of the PI controller
        ego_y = env.ego_vehicle.get_location().y
        ego_x = env.ego_vehicle.get_location().x
        ego_yaw = env.ego_vehicle.get_transform().rotation.yaw
        threshold = 10 if (205 < ego_y < 215) or (230 < ego_y < 240) else 1
        colli_risk = (abs(ego_x - path_generator(np.clip(ego_y, 200, 250))) > threshold)
        left_risk = (ego_x > 338.5) and (ego_yaw < 90)
        right_risk = (ego_x < 335) and (ego_yaw > 90)
        
        if not pid_guide:
            pid_intergal = 0
        
        if (colli_risk or left_risk or right_risk) and (step != 0) and (i % 3 == pid_seed):
            pid_guide = True
            xreal = scope['position_x']
            xref = path_generator(np.clip(scope['position_y'], 200, 250))
            pid_intergal += (xreal - xref)
            pid_proportional = xreal - xref
            action = np.clip(0.3 * (pid_proportional) + 0.0 * (pid_intergal), -1, 1)
        else:
            pid_guide = False
        ## End of Section pid controller ##


        ## Section environment update ##
        State_, action_fdbk, reward_e, _, done, scope = env.run_step(action)
        # action_fdbk is not None if human participants manipulate the steering wheel
        list_fdbk.append(action_fdbk)
        ## End of Section environment update ##


        ## Section reward shaping ##
        # intervention penalty-based shaping
        if REWARD_SHAPING == 1:
            # only the 1st intervened time step is penalized
            if (action_fdbk is not None) or (pid_guide is True):
                if step_intervene == 0:
                    reward_i = -10
                    step_intervene += 1
                else:
                    reward_i = 0
            else:
                reward_i = 0
                step_intervene = 0
        # heuristic potential-based shaping
        elif REWARD_SHAPING == 2:
            reward_i = 250 - ego_y
        # RND shaping
        elif REWARD_SHAPING == 3:
            error, mu, std = rnd.forward(State_)
            reward_i = (min(max(1 + (error - mu) / std, 0.35), 2) - 0.35) * 10
        # no shaping
        else:
            reward_i = 0
        reward = reward_e + reward_i
        ## End of Section reward shaping ##


        ## Section DRL store ##
        # human intervention event occurs
        if action_fdbk is not None:
            # record the q difference of the 1st time step of one human intervention event
            if (flag_qrecord == 0) and (list_fdbk[-2] is None):
                bs = torch.tensor(State,dtype=torch.float).view(1, env.observation_size_height, env.observation_size_width).to(device)
                ba = torch.tensor(DRL.actor(bs),dtype=torch.float).to(device)
                q1, q2 = DRL.critic([bs, ba])
                qlist.append([q1.detach().cpu().numpy(), q2.detach().cpu().numpy()])
            # record the action difference of one human intervention event    
            action_disturbing_degree.append([action_fdbk, float(action)])
            intervene_percent_per_episode[i].append(action_fdbk)

            action = action_fdbk

            intervention = 1
            DRL.store_transition(State, action, action_fdbk, intervention, reward, State_)
        # PI controller event occurs
        elif pid_guide is True:
            intervention = 1
            if flag_qrecord == 0:
                bs = torch.tensor(State,dtype=torch.float).view(1, env.observation_size_height, env.observation_size_width).to(device)
                ba = torch.tensor(action,dtype=torch.float).unsqueeze(0).unsqueeze(0).to(device)
                q1, q2 = DRL.critic([bs, ba])
                qlist.append([q1.detach().cpu().numpy(), q2.detach().cpu().numpy()])
                flag_qrecord = 1
            
            intervene_percent_per_episode[i].append(action)

            DRL.store_transition(State, action, action_fdbk, intervention, reward, State_)
        # No intervention occurs
        else:
            intervention = 0
            DRL.store_transition(State, action, action_fdbk, intervention, reward, State_)
        ## End of DRL store ##


        ## Section DRL update ##
        learn_threshold = 5000 if PRE_EXPLORATION else 256
        if total_step > learn_threshold:
            c_loss, a_loss = DRL.learn(epoch=i)
            loss_critic.append(np.average(c_loss))
            loss_actor.append(np.average(a_loss))
            # Decrease the exploration rate
            var = var * 0.99988 if var>0.05 else 0.05
        ## End of Section DRL update ##


        ep_reward += reward
        global_reward_list.append([reward_e,reward_i])
        reward_e_record[i].append(reward_e)
        reward_i_record[i].append(reward_i)
        
        final_action[i].append(action)

        x_per_episode[i].append(scope['position_x'])
        y_per_episode[i].append(scope['position_y'])

        State = State_

        total_step += 1
        step += 1
        
        if done:
            
            mean_reward =  ep_reward / step  
            episode_reward_list.append(mean_reward)
            episode_duration_list.append(step)
            intervene_percent.append(len(intervene_percent_per_episode[i]))

            # print('\n episode is:',i)
            # print('explore_rate:',round(var,4))
            # print('c_loss:',round(np.average(c_loss),4))
            # print('a_loss',round(np.average(a_loss),4))
            # print('total_step:',total_step)
            # print('episode_step:',step)
            
            writer.add_scalar('reward/reward_episode', mean_reward, i)
            writer.add_scalar('reward/reward_episode_noshaping', np.mean(reward_e_record[i]), i)
            writer.add_scalar('reward/duration_episode', step, i)
            writer.add_scalar('percent_intervene', len(intervene_percent_per_episode[i]), i)
            writer.add_scalar('rate_exploration', round(var,4), i)
            writer.add_scalar('loss/loss_critic', round(np.average(c_loss),4), i)
            writer.add_scalar('loss/loss_actor', round(np.average(a_loss),4), i)
            
            break
        
        signal.signal(signal.SIGINT, signal_handler)

            
    if total_step > MAX_STEPS:
        break 

print('total time:',time.perf_counter()-start_time)        
        
DRL.save_model('./TD3_based_DRL/models')

pygame.display.quit()
pygame.quit()

action_drl = previous_action[0:i]
action_final = final_action[0:i]
scio.savemat('data{}-{}.mat'.format(algorithm,round(time.time())), mdict={'action_drl': action_drl,'action_final': action_final,
                                                'actiondisturbingdegree':action_disturbing_degree,
                                                'qlist':qlist,'intervenepercent':intervene_percent,
                                                'x':x_per_episode,'y':y_per_episode,'stepreward':global_reward_list,
                                                'step':episode_duration_list,'reward':episode_reward_list,
                                                'r_i':reward_i_record,'r_e':reward_e_record})

!!! env.py  !!!

''' 
This environment describe a fixed scene (area) to conduct end-to-end lateral control tasks
for the autonomous ego vehicle. (This environment is relative simple and is only for training)
'''

import pygame
import weakref
import collections
import numpy as np
import math
import cv2
import sys
'''
Add your path of the CARLA simulator below.
This script was originally run with CARLA(0.9.7), some functions (e.g., carla.set_velocity()) have been removed in the newer CARLA. 
Please refer to CARLA official documents for detail if you want to run the script with a different version.
'''
sys.path.append('xxx/carla-0.9.X-py3.X-linux-x86_64.egg')

import carla
from carla import ColorConverter as cc

if sys.version_info >= (3, 0):
    from configparser import ConfigParser
else:
    from ConfigParser import RawConfigParser as ConfigParser

from utils import get_path
path_generator = get_path()

velocity_target_ego = 5
x_bench = 335.0
y_bench = 200.0
WIDTH, HEIGHT = 80, 45

class scenario(object):
    def __init__(self, random_spawn=True, pedestrian=False, no_render=False, frame=25):

        self.observation_size_width = WIDTH
        self.observation_size_height = HEIGHT
        self.observation_size = WIDTH * HEIGHT
        self.action_size = 1

        ## set the carla World parameters
        self.pedestrian = pedestrian
        self.random_spawn = random_spawn
        self.no_render = no_render

        ## set the vehicle actors
        self.ego_vehicle = None
        self.obs1 = None
        self.obs2 = None
        self.obs3 = None

        ## set the sensory actors
        self.collision_sensor = None
        self.seman_camera = None
        self.viz_camera = None
        self.surface = None
        self.camera_output = np.zeros([720,1280,3])
        self.recording = False
        self.Attachment = carla.AttachmentType

        ## connect to the CARLA client
        self.client = carla.Client('localhost',2000)
        self.client.set_timeout(10.0)
        
        ## build the CARLA world
        self.world = self.client.load_world('Town01')
        settings = self.world.get_settings()
        settings.fixed_delta_seconds = 1/frame
        settings.no_rendering_mode = self.no_render
        settings.synchronous_mode = True
        self.world.apply_settings(settings)
        
        ## initialize the pygame settings
        pygame.init()
        pygame.font.init()
        pygame.joystick.init()
        self.display = pygame.display.set_mode((1280, 720),pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.infoObject = pygame.display.Info()

        ## initilize the joystick settings
        self._joystick = pygame.joystick.Joystick(0)
        self._joystick.init()
            
        self._parser = ConfigParser()
        self._parser.read('./wheel_config.ini')
        self._steer_idx = int(self._parser.get('G29 Racing Wheel', 'steering_wheel'))
        self._throttle_idx = int(self._parser.get('G29 Racing Wheel', 'throttle'))
        self._brake_idx = int(self._parser.get('G29 Racing Wheel', 'brake'))
        self._reverse_idx = int(self._parser.get('G29 Racing Wheel', 'reverse'))
        self._handbrake_idx = int(self._parser.get('G29 Racing Wheel', 'handbrake'))

        self.restart()

    def restart(self):

        ## reset the recording lists
        self.steer_history = []
        self.intervene_history = []

        ## reset the human intervention state
        self.intervention = False

        ## spawn three surrounding vehicles
        self.bp_obs1, self.spawn_point_obs1 = self._produce_vehicle_blueprint(1, 335.0+3.5, 100.0)
        self.obs1 = self.world.spawn_actor(self.bp_obs1,self.spawn_point_obs1)

        self.bp_obs2, self.spawn_point_obs2 = self._produce_vehicle_blueprint(1, 335.0, 200.0+25.0)
        self.obs2 = self.world.spawn_actor(self.bp_obs2,self.spawn_point_obs2)

        self.bp_obs3, self.spawn_point_obs3 = self._produce_vehicle_blueprint(1, 335.0+3.5, 200.0+50.0)
        self.obs3 = self.world.spawn_actor(self.bp_obs3,self.spawn_point_obs3)

        ## if pedestrians are considered, spawn two persons 
        if self.pedestrian:
            self.bp_walker1, self.spawn_point_walker1 = self._produce_walker_blueprint(338.0, 200+np.random.randint(10,15))
            self.bp_walker2, self.spawn_point_walker2 = self._produce_walker_blueprint(np.random.randint(3310,3350)/10, 235)

            self.walker1 = self.world.spawn_actor(self.bp_walker1, self.spawn_point_walker1)
            self.walker2 = self.world.spawn_actor(self.bp_walker2, self.spawn_point_walker2)

            walker1_control = carla.WalkerControl()
            walker1_control.speed = 0.1
            self.walker1.apply_control(walker1_control)

            walker2_control = carla.WalkerControl()
            walker2_control.speed = 0.1
            self.walker2.apply_control(walker2_control)
        
        ## spawn the ego vehicle (random / fixed)
        if self.random_spawn:
            y_spawn_random = np.random.randint(200, 240)
            random_lateral_disturb = 0.1 * (np.random.rand()-0.5)
            x_spwan_random = path_generator(y_spawn_random) + random_lateral_disturb
            self.bp_ego, self.spawn_point_ego = self._produce_vehicle_blueprint(1, x_spwan_random, y_spawn_random)
        else:
            self.bp_ego, self.spawn_point_ego = self._produce_vehicle_blueprint(1 , x_bench, y_bench)
        self.ego_vehicle = self.world.spawn_actor(self.bp_ego,self.spawn_point_ego)
        
        # set the initial velocity of the ego vehicle
        initial_velocity = carla.Vector3D(0, velocity_target_ego, 0)
        self.ego_vehicle.set_velocity(initial_velocity)

        # initilize the control variable for the ego vehicle
        self.control = carla.VehicleControl()


        ## configurate and spawn the collision sensor
        # clear the collision history list
        self.collision_history = []
        bp_collision = self.world.get_blueprint_library().find('sensor.other.collision')
        # spawn the collision sensor actor
        if self.collision_sensor is not None:
            self.collision_sensor.destroy()
        self.collision_sensor = self.world.spawn_actor(
                bp_collision, carla.Transform(), attach_to=self.ego_vehicle)
        # obtain the collision signal and append to the history list
        weak_self = weakref.ref(self)
        self.collision_sensor.listen(lambda event: scenario._on_collision(weak_self, event))

        
        ## configurate and spawn the camera sensors
        # the candidated transform of camera's position: frontal
        self.camera_transforms = [
            (carla.Transform(carla.Location(x=-2, z=5), carla.Rotation(pitch=30.0)), self.Attachment.SpringArm),
            (carla.Transform(carla.Location(x=-2, z=5), carla.Rotation(pitch=30.0)), self.Attachment.SpringArm)]
        self.camera_transform_index = 1
        # the candidated camera type: rgb (viz_camera) and semantic (seman_camera)
        self.cameras = [
            ['sensor.camera.rgb', cc.Raw, 'Camera RGB', {}],
            ['sensor.camera.semantic_segmentation', cc.CityScapesPalette,
                'Camera Semantic Segmentation (CityScapes Palette)', {}]
            ]
                
        bp_viz_camera = self.world.get_blueprint_library().find('sensor.camera.rgb')
        bp_viz_camera.set_attribute('image_size_x', '1280')
        bp_viz_camera.set_attribute('image_size_y', '720')
        bp_viz_camera.set_attribute('sensor_tick', '0.02')
        self.cameras[0].append(bp_viz_camera)

        bp_seman_camera = self.world.get_blueprint_library().find('sensor.camera.semantic_segmentation')
        bp_seman_camera.set_attribute('image_size_x', '1280')
        bp_seman_camera.set_attribute('image_size_y', '720')
        bp_seman_camera.set_attribute('sensor_tick', '0.04')
        self.cameras[1].append(bp_seman_camera)
        

        # spawn the camera actors
        if self.seman_camera is not None:
            self.seman_camera.destroy()
            self.surface = None

        self.viz_camera = self.world.spawn_actor(
            self.cameras[0][-1],
            self.camera_transforms[self.camera_transform_index][0],
            attach_to=self.ego_vehicle,
            attachment_type=self.Attachment.SpringArm)

        self.seman_camera = self.world.spawn_actor(
            self.cameras[1][-1],
            self.camera_transforms[self.camera_transform_index - 1][0],
            attach_to=self.ego_vehicle,
            attachment_type=self.camera_transforms[self.camera_transform_index - 1][1])

        # obtain the camera image
        weak_self = weakref.ref(self)
        self.seman_camera.listen(lambda image: scenario._parse_seman_image(weak_self, image))
        self.viz_camera.listen(lambda image: scenario._parse_image(weak_self, image))

        
        ## reset the step counter
        self.count = 0

    
    def render(self, display):
        if self.surface is not None:
            m = pygame.transform.smoothscale(self.surface, 
                                 [int(self.infoObject.current_w), 
                                  int(self.infoObject.current_h)])
            display.blit(m, (0, 0))


    def _parse_seman_image(weak_self, image):
        self = weak_self()
        if not self:
            return
        image.convert(self.cameras[1][1])
        array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
        array = np.array(image.raw_data)
        array = np.reshape(array, (image.height, image.width, 4))
        array = array[:, :, :3]
        array = array[:, :, ::-1]
        
        self.camera_output = array
    

    def _parse_image(weak_self, image):
        self = weak_self()
        if not self:
            return
        image.convert(self.cameras[0][1])
        array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
        array = np.array(image.raw_data)
        array = np.reshape(array, (image.height, image.width, 4))
        array = array[:, :, :3]
        array = array[:, :, ::-1]
        self.surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
    
    
    def _on_collision(weak_self, event):
        self = weak_self()
        if not self:
            return
        impulse = event.normal_impulse
        intensity = math.sqrt(impulse.x**2 + impulse.y**2 + impulse.z**2)
        self.collision_history.append((event.frame, intensity))
        if len(self.collision_history) > 4000:
            self.collision_history.pop(0)


    def get_collision_history(self):
        collision_history = collections.defaultdict(int)
        flag = 0
        for frame, intensity in self.collision_history:
            collision_history[frame] += intensity
            if intensity != 0:
                flag = 1
        return collision_history, flag
    
    
    def run_step(self,action):

        self.render(self.display)
        pygame.display.flip()
        
        self.parse_events()

        human_control = None
        
        # retrive the signals from the joystick (steering wheel)
        numAxes = self._joystick.get_numaxes()
        jsInputs = [float(self._joystick.get_axis(i)) for i in range(numAxes)]

        ## if no human intervention
        if not self.intervention:
            steerCmd = action / 2
            self.control.steer = math.tan(1.1 * steerCmd)
        ## if intervention detected, convert the joystick signal to the steering command
        else:
            K1 = 1
            steerCmd = K1 * (2 * jsInputs[self._steer_idx])
            self.control.steer = steerCmd

            human_control = self.control.steer
        
        ## detect the intervention signal
        if len(self.steer_history) > 2:
            # the intervention is activated if human participants move the joystick
            if abs(self.intervene_history[-2] - self.intervene_history[-1]) > 0.02:
                self.intervention = True
        if len(self.steer_history) > 5:
            # the intervention is deactivated if the joystick continue to be stable for 0.2 seconds
            if abs(self.intervene_history[-5] - self.intervene_history[-1]) < 0.01:
                self.intervention = False

        ## record the intervention histroy (get "None" for non-intervened steps)
        self.intervene_history.append(jsInputs[0])
        
        # record the steering command history
        self.steer_history.append(steerCmd)
        
        ## configurate the control command for the ego vehicle
        # the velocity is calculated as :sqrt(vx**2+vy**2)
        velocity_ego = ((self.ego_vehicle.get_velocity().x)**2 + (self.ego_vehicle.get_velocity().y)**2)**(1/2)
        
        # the longitudinal control (throttle) of the ego vehicle is achieved by a proportional controller
        self.control.throttle = np.clip (velocity_target_ego - velocity_ego, 0, 1)
        self.control.brake = 0
        self.control.hand_brake = 0

        ## achieve the control to the ego vehicle
        self.ego_vehicle.apply_control(self.control)

        ## obtain the state transition and other variables after taking the action (control command)
        next_states, other_indicators = self.obtain_observation()

        ## detect if the step is the terminated step, by considering: collision, beyond the road, and episode fininsh
        collision = self.get_collision_history()[1]
        finish = (self.ego_vehicle.get_location().y > y_bench + 55.0)
        beyond = (self.ego_vehicle.get_location().x < x_bench - 1.2) or (self.ego_vehicle.get_location().x > x_bench + 4.8)
        done = collision or finish or beyond

        ## calculate the relative distance to the surrounding vehicles for the subsequent reward function
        dis_to_front = other_indicators['state_front']
        dis_to_side = min(other_indicators['state_left'],other_indicators['state_right'])
        dis_to_obs11 = other_indicators['state_corner_11']
        dis_to_obs12 = other_indicators['state_corner_12']
        dis_to_obs21 = other_indicators['state_corner_21']
        dis_to_obs22 = other_indicators['state_corner_22']
        dis_to_obs31 = other_indicators['state_corner_31']
        dis_to_obs32 = other_indicators['state_corner_32']
        
        ## calculate the reward signal of the step: r1-r3 distance reward, r4 terminal reward, r5-r6 smooth reward
        r1 = -1*np.square(1-dis_to_front)
        r2 = -2*np.square(1-dis_to_side)
        r3 = - (np.abs(1-dis_to_obs11)+np.abs(1-dis_to_obs12)+np.abs(1-dis_to_obs21)+np.abs(1-dis_to_obs22)+np.abs(1-dis_to_obs31)+np.abs(1-dis_to_obs32))
        r4 = finish*10 - collision*10 - beyond*10
        r5= -np.float32(abs(self.steer_history[-1]-steerCmd)>0.1)
        r6 = -3*abs(steerCmd)
        
        reward = r1+r2+r3+r4+r5+r6+0.2
        reward = np.clip(reward,-10,10)
        
        ## update the epsodic step
        self.count += 1
        
        ## record the physical variables
        yaw_rate = np.arctan(self.ego_vehicle.get_velocity().x/self.ego_vehicle.get_velocity().y) if self.ego_vehicle.get_velocity().y > 0 else 0
        physical_variables = {'velocity_y':self.ego_vehicle.get_velocity().y,
                 'velocity_x':self.ego_vehicle.get_velocity().x,
                 'position_y':self.ego_vehicle.get_location().y,
                 'position_x':self.ego_vehicle.get_location().x,
                 'yaw_rate':yaw_rate,
                 'yaw':self.ego_vehicle.get_transform().rotation.yaw,
                 'pitch':self.ego_vehicle.get_transform().rotation.pitch,
                 'roll':self.ego_vehicle.get_transform().rotation.roll,
                 'angular_velocity_y':self.ego_vehicle.get_angular_velocity().y,
                 'angular_velocity_x':self.ego_vehicle.get_angular_velocity().x
                 }
        
        if done:
            self.destroy()
            
        return next_states, human_control, reward, self.intervention, done, physical_variables
    

    def destroy(self):
        actors = [
            self.ego_vehicle,
            self.obs1,
            self.obs2,
            self.obs3,
            self.seman_camera,
            self.viz_camera,
            self.collision_sensor]
        self.seman_camera.stop()
        self.viz_camera.stop()
        for actor in actors:
            if actor is not None:
                actor.destroy()


    def obtain_observation(self):
        ## obtain image-based state space
        # state variable sets
        state_space = self.camera_output[:,:,0]
        state_space = cv2.resize(state_space,(WIDTH, HEIGHT))
        state_space = np.resize(state_space,(self.observation_size, 1))
        state_space = np.squeeze(state_space)/255
        
        ## obtain space variables for reward generation
        velocity_self = self.ego_vehicle.get_velocity()
        position_self = self.ego_vehicle.get_location()
        yaw_self = self.ego_vehicle.get_transform().rotation.yaw
        position_obs1 = self.obs1.get_location()
        position_obs2 = self.obs2.get_location()
        position_obs3 = self.obs3.get_location()

        ## obtain relative distance information for reward generation
        # pre-calculated parameters
        xa,ya,xb,yb,xc,yc,xd,yd = self._to_corner_coordinate(position_self.x,position_self.y,yaw_self)
        xfc = (xa+xb)/2
        yfc = (ya+yb)/2
        xa1,ya1,xb1,yb1,xc1,yc1,xd1,yd1 = 337.4,202.4,339.6,202.4,339.6,197.6,337.4,197.6
        xa2,ya2,xb2,yb2,xc2,yc2,xd2,yd2 = 333.9,227.4,336.1,227.4,336.1,222.6,333.9,222.6
        xa3,ya3,xb3,yb3,xc3,yc3,xd3,yd3 = 337.4,252.4,339.6,252.4,339.6,247.6,337.4,247.6
        
        # relative distance from ego vehicle to obstacle 1 (corner distance)
        if position_obs1.y - 4 < position_self.y < position_obs1.y + 4:
            state_corner_11 = self._sigmoid(np.clip(abs(xa1-xa),0,10),2.5)
            state_corner_12 = self._sigmoid(np.clip(abs(xa1-xb),0,10),2.5)
        else:
            state_corner_11 = 1
            state_corner_12 = 1
        # relative distance from ego vehicle to obstacle 2 (corner distance)
        if position_obs2.y - 4 < position_self.y < position_obs2.y + 4:
            state_corner_21 = self._sigmoid(np.clip(abs(xb2-xa),0,10),2.5)
            state_corner_22 = self._sigmoid(np.clip(abs(xb2-xb),0,10),2.5)
        else:
            state_corner_21 = 1
            state_corner_22 = 1
        # relative distance from ego vehicle to obstacle 3 (corner distance)
        if position_obs3.y - 4 < position_self.y < position_obs3.y + 4:
            state_corner_31 = self._sigmoid(np.clip(abs(xa3-xa),0,10),2.5)
            state_corner_32 = self._sigmoid(np.clip(abs(xa3-xb),0,10),2.5)
        else:
            state_corner_31 = 1
            state_corner_32 = 1
        # relative distance to both sides of road
        state_left = self._sigmoid(np.clip(340-xb,0,10),2)
        state_right = self._sigmoid(np.clip(xb-332,0,10),2)
        # relative distance front
        RIGHT = 1 if position_self.x < x_bench + 1.8 else 0
        if RIGHT:
            if position_self.y < y_bench + 25.0:
                state_front = np.clip(yc2 - position_self.y - 2.6, 0, 25)
                state_front = self._sigmoid(state_front,1)
            else:
                state_front = 1
        else:
            state_front = np.clip(yc3 - position_self.y - 2.4, 0,25)
            state_front = self._sigmoid(state_front,1)
    
        # other indicators facilitating producing reward function signal
        other_indicators = {'state_front':state_front,
                            'state_left':state_left,
                            'state_right':state_right,
                            'state_corner_11':state_corner_11,
                            'state_corner_12':state_corner_12,
                            'state_corner_21':state_corner_21,
                            'state_corner_22':state_corner_22,
                            'state_corner_31':state_corner_31,
                            'state_corner_32':state_corner_32}
        
        return state_space, other_indicators
    

    def obtain_real_observation(self):
        state_space = self.camera_output[:,:,0]
        return state_space
        

    def parse_events(self):
        for event in pygame.event.get():
            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 0:
                    self.intervention = False
                elif event.button == self._reverse_idx:
                    self.control.gear = 1 if self.control.reverse else -1
                elif event.button == 1:
                    self._toggle_camera()
                elif event.button == 2:
                    self._next_sensor()


    def _produce_vehicle_blueprint(self, color, x, y, vehicle='bmw'):
        if vehicle=='bmw':
            bp = self.world.get_blueprint_library().filter('vehicle.bmw.*')[0]
        elif vehicle=='moto':
            bp = self.world.get_blueprint_library().filter('vehicle.harley-davidson.*')[0]
        elif vehicle=='bike':
            bp = self.world.get_blueprint_library().filter('vehicle.diamondback.century.*')[0]
        elif vehicle=='bus':
            bp = self.world.get_blueprint_library().filter('vehicle.volkswagen.*')[0]
        else:
            bp = self.world.get_blueprint_library().filter('vehicle.lincoln.*')[0]
        
        bp.set_attribute('color', bp.get_attribute('color').recommended_values[color])

        spawn_point = self.world.get_map().get_spawn_points()[0]
        spawn_point.location.x = x
        spawn_point.location.y = y
        spawn_point.location.z += 0.1

        return bp, spawn_point
    
    def _produce_walker_blueprint(self, x, y):
        
        bp = self.world.get_blueprint_library().filter('walker.*')[np.random.randint(2)]
        
        spawn_point = self.world.get_map().get_spawn_points()[0]
        spawn_point.location.x = x
        spawn_point.location.y = y
        spawn_point.location.z += 0.1      
        spawn_point.rotation.yaw = 0
        
        return bp, spawn_point
        
    def _toggle_camera(self):
        self.camera_transform_index = (self.camera_transform_index + 1) % len(self.camera_transforms)
    
    def _next_sensor(self):
        self.camera_index += 1
        
    def _dis_p_to_l(self,k,b,x,y):
        dis = abs((k*x-y+b)/math.sqrt(k*k+1))
        return self._sigmoid(dis,2)
    
    def _calculate_k_b(self,x1,y1,x2,y2):
        k = (y1-y2)/(x1-x2)
        b = (x1*y2-x2*y1)/(x1-x2)
        return k,b
    
    def _dis_p_to_p(self,x1,y1,x2,y2):
        return math.sqrt((x1-x2)**2+(y1-y2)**2)
    
    def _to_corner_coordinate(self,x,y,yaw):
        xa = x+2.64*math.cos(yaw*math.pi/180-0.43)
        ya = y+2.64*math.sin(yaw*math.pi/180-0.43)
        xb = x+2.64*math.cos(yaw*math.pi/180+0.43)
        yb = y+2.64*math.cos(yaw*math.pi/180+0.43)
        xc = x+2.64*math.cos(yaw*math.pi/180-0.43+math.pi)
        yc = y+2.64*math.cos(yaw*math.pi/180-0.43+math.pi)
        xd = x+2.64*math.cos(yaw*math.pi/180+0.43+math.pi)
        yd = y+2.64*math.cos(yaw*math.pi/180+0.43+math.pi)
        return xa,ya,xb,yb,xc,yc,xd,yd
    
    def _sigmoid(self,x,theta):
        return 2./(1+math.exp(-theta*x))-1


!!! Folder TD3_based_DRL !!!

!!! util.py !!!

import os
import torch
from torch.autograd import Variable

def soft_update(target, source, tau):
    for target_param, param in zip(target.parameters(), source.parameters()):
        target_param.data.copy_(
            target_param.data * (1.0 - tau) + param.data * tau
        )

def hard_update(target, source):
    for target_param, param in zip(target.parameters(), source.parameters()):
            target_param.data.copy_(param.data)
            

!!! priority_replay.py !!!

import warnings
warnings.filterwarnings('ignore')
import numpy as np

class SumTree(object):
    """
    This SumTree code is modified version and the original code is from: 
    https://github.com/jaara/AI-blog/blob/master/SumTree.py
    Story the data with it priority in tree and data frameworks.
    """
    data_pointer = 0

    def __init__(self, capacity):
        self.capacity = capacity  # for all priority values
        self.tree = np.zeros(2 * capacity - 1)
        # [--------------Parent nodes-------------][-------leaves to recode priority-------]
        #             size: capacity - 1                       size: capacity
        self.data = np.zeros(capacity, dtype=object)  # for all transitions
        # [--------------data frame-------------]
        #             size: capacity
        self.total_n = 0

    def add(self, p, data):
        tree_idx = self.data_pointer + self.capacity - 1
        self.data[self.data_pointer] = data  # update data_frame
        self.update(tree_idx, p)  # update tree_frame

        self.data_pointer += 1
        if self.data_pointer >= self.capacity:  # replace when exceed the capacity
            self.data_pointer = 0
        self.total_n += 1

    def update(self, tree_idx, p):
        change = p - self.tree[tree_idx]
        self.tree[tree_idx] = p
        # then propagate the change through tree
        while tree_idx != 0:    # this method is faster than the recursive loop in the reference code
            tree_idx = (tree_idx - 1) // 2
            self.tree[tree_idx] += change

    def get_leaf(self, v):
        """
        Tree structure and array storage:
        Tree index:
             0         -> storing priority sum
            / \
          1     2
         / \   / \
        3   4 5   6    -> storing priority for transitions
        Array type for storing:
        [0,1,2,3,4,5,6]
        """
        parent_idx = 0
        while True:     # the while loop is faster than the method in the reference code
            cl_idx = 2 * parent_idx + 1         # this leaf's left and right kids
            cr_idx = cl_idx + 1
            if cl_idx >= len(self.tree):        # reach bottom, end search
                leaf_idx = parent_idx
                break
            else:       # downward search, always search for a higher priority node
                if v <= self.tree[cl_idx]:
                    parent_idx = cl_idx
                else:
                    v -= self.tree[cl_idx]
                    parent_idx = cr_idx

        data_idx = leaf_idx - self.capacity + 1
        return leaf_idx, self.tree[leaf_idx], self.data[data_idx]

    @property
    def total_p(self):
        return self.tree[0]  # the root


class Memory(object):  # stored as ( s, a, r, s_ ) in SumTree
    """
    This SumTree code is modified version and the original code is from:
    https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py
    """
    epsilon = 0.001  # small amount to avoid zero priority
    alpha = 0.6  # [0~1] convert the importance of TD error to priority
    beta = 0.4  # importance-sampling, from initial value increasing to 1
    beta_increment_per_sampling = 0.001
    abs_err_upper = 10.  # clipped abs error

    def __init__(self, capacity):
        self.tree = SumTree(capacity)

    def store(self, transition):
        max_p = np.max(self.tree.tree[-self.tree.capacity:])
        if max_p == 0:
            max_p = self.abs_err_upper
        self.tree.add(max_p, transition)   # set the max p for new p

    def sample(self, n):
        b_idx, b_memory, ISWeights = np.empty((n,), dtype=np.int32), np.empty((n, self.tree.data[0].size)), np.empty((n, 1))
        pri_seg = self.tree.total_p / n       # priority segment
        self.beta = np.min([1., self.beta + self.beta_increment_per_sampling])  # max = 1

        nonzeros = self.tree.tree[-self.tree.capacity:]
        pointer = self.tree.data_pointer -1 if self.tree.total_n<self.tree.capacity else self.tree.capacity-1
        nonzeros = nonzeros[:pointer]
        min_prob = max(np.min(nonzeros) / self.tree.total_p, self.epsilon)

        # min_prob = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.total_p     # for later calculate ISweight
        for i in range(n):
            a, b = pri_seg * i, pri_seg * (i + 1)
            p = 0
            v = np.random.uniform(a, b)
            idx, p, data = self.tree.get_leaf(v)
            while p==0:
                v = v-1
                idx, p, data = self.tree.get_leaf(v)
            prob = p / self.tree.total_p
            ISWeights[i, 0] = np.power(prob/min_prob, -self.beta)
            # if ISWeights[i, 0] == 0 or np.isnan(ISWeights[i,0]) or np.isinf(ISWeights[i,0]):
            #     ISWeights[i, 0] = 1
            b_idx[i], b_memory[i, :] = idx, data
        return b_idx, b_memory, ISWeights

    def batch_update(self, tree_idx, abs_errors):
        abs_errors += self.epsilon  # convert to abs and avoid 0
        clipped_errors = np.minimum(abs_errors, self.abs_err_upper)
        ps = np.power(clipped_errors, self.alpha)
        for ti, p in zip(tree_idx, ps):
            self.tree.update(ti, p)


!!! network_model.py !!!

import numpy as np

import torch
import torch.nn as nn
import torch.nn.functional as F

seed = 2
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

### This actor network is established on CNN structure for the image-style state with the shape of 80*45.
class Actor(nn.Module):
    def __init__(self, nb_states, nb_actions, hidden=32, init_w=3e-1):
        super(Actor,self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 6)
        self.conv2 = nn.Conv2d(6, 16, 6)
        self.fc1 = nn.Linear(16*16*7, 256)
        self.fc2 = nn.Linear(256, 128)
        self.fc3 = nn.Linear(128, 64)
        self.fc4 = nn.Linear(64, nb_actions)
        self.relu = nn.ReLU()
        self.sig = nn.Tanh()
        self.init_weights(init_w)
        
    def init_weights(self,init_w):

        torch.nn.init.kaiming_uniform_(self.fc1.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')    
        torch.nn.init.kaiming_uniform_(self.fc2.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc3.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        self.fc4.weight.data.uniform_(-init_w,init_w)
        
    def forward(self,inp):
        
        x = inp.unsqueeze(1)
        x = F.max_pool2d( self.conv1(x), 2)
        x = F.max_pool2d( self.conv2(x), 2)
        x = x.view(x.size(0), 16*16*7)
        
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        x = self.relu(x)
        x = self.fc3(x)
        x = self.relu(x)
        x = self.fc4(x)
        out = self.sig(x)
        return out

### This critic network is established on MLP structure.
class Critic(nn.Module):
    def __init__(self, nb_states, nb_actions, hidden=256, init_w=3e-1):
        super(Critic,self).__init__()

        self.fc1 = nn.Linear(nb_states,hidden)
        self.fc2 = nn.Linear(hidden+nb_actions,hidden)
        self.fc3 = nn.Linear(hidden,hidden)
        self.fc4 = nn.Linear(hidden,hidden)
        self.fc5 = nn.Linear(hidden,1)
        
        self.fc11 = nn.Linear(nb_states,hidden)
        self.fc21 = nn.Linear(hidden+nb_actions,hidden)
        self.fc31 = nn.Linear(hidden,hidden)
        self.fc41 = nn.Linear(hidden,hidden)
        self.fc51 = nn.Linear(hidden,1)
        
        self.relu = nn.ReLU()

        self.init_weights(init_w)
        
    def init_weights(self,init_w):

        torch.nn.init.kaiming_uniform_(self.fc1.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc2.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc3.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc4.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        self.fc5.weight.data.uniform_(-init_w,init_w)
        
        torch.nn.init.kaiming_uniform_(self.fc11.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc21.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc31.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        torch.nn.init.kaiming_uniform_(self.fc41.weight.data, a=0, mode='fan_in', nonlinearity='leaky_relu')
        self.fc51.weight.data.uniform_(-init_w,init_w)
        
    def forward(self,inp):

        x,a = inp
        x = x.view(x.size(0),45*80)
        q1 = self.fc1(x)
        q1 = self.relu(q1)
        q1 = self.fc2(torch.cat([q1,a],1))
        q1 = self.relu(q1)
        q1 = self.fc3(q1)
        q1 = self.relu(q1)
        q1 = self.fc4(q1)
        q1 = self.relu(q1)
        q1 = self.fc5(q1)
        
        q2 = self.fc11(x)
        q2 = self.relu(q2)
        q2 = self.fc21(torch.cat([q2,a],1))
        q2 = self.relu(q2)
        q2 = self.fc31(q2)
        q2 = self.relu(q2)
        q2 = self.fc41(q2)
        q2 = self.relu(q2)
        q2 = self.fc51(q2)
        
        return q1,q2


!!! TD3HUG.py  !!!

import pickle
import numpy as np

import torch
import torch.nn as nn

from TD3_based_DRL.priority_replay import Memory
from TD3_based_DRL.network_model import Actor,Critic
from TD3_based_DRL.util import hard_update, soft_update

seed = 2
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

## Hyperparameters
MEMORY_CAPACITY = 38400
BATCH_SIZE = 128
GAMMA = 0.95
LR_C = 0.0005
LR_A = 0.0002
TAU = 0.001
POLICY_NOSIE = 0.2
POLICY_FREQ = 1
NOISE_CLIP = 0.5

class DRL:
        
    def __init__(self, action_dim, state_dim, LR_C = LR_C, LR_A = LR_A):

        self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
        
        # Hyperparameters configuration
        self.state_dim = state_dim[0] * state_dim[1]
        self.state_dim_width = state_dim[0]
        self.state_dim_height = state_dim[1]
        self.action_dim = action_dim
        self.batch_size = BATCH_SIZE
        self.gamma = GAMMA
        self.tau = TAU
        self.policy_noise = POLICY_NOSIE
        self.noise_clip = NOISE_CLIP
        self.policy_freq = POLICY_FREQ
        self.itera = 0

        # Priority Experience Replay Buffer
        self.pointer = 0
        self.memory = Memory(MEMORY_CAPACITY)
        
        self.actor = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_target = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),LR_A)
        
        self.critic = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_target = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_optimizers = torch.optim.Adam(self.critic.parameters(),LR_C)
        
        hard_update(self.actor_target,self.actor)
        hard_update(self.critic_target,self.critic)
        
            
    def learn(self, batch_size = BATCH_SIZE, epoch=0):

        ## batched state, batched action, batched action from expert, batched intervention signal, batched reward, batched next state
        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(batch_size)
        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        ba = torch.tensor(ba, dtype=torch.float).to(self.device)
        ba_e = torch.tensor(ba_e, dtype=torch.float).to(self.device)
        br = torch.tensor(br, dtype=torch.float).to(self.device)
        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)

        # initialize the loss variables
        loss_c, loss_a = 0, 0

        ## calculate the predicted values of the critic
        with torch.no_grad():
            noise1 = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)
            a_ = (self.actor_target(bs_).detach() + noise1).clamp(0, 1)
            target_q1, target_q2 = self.critic_target([bs_,a_])
            target_q1 = target_q1.detach()
            target_q2 = target_q2.detach()
            target_q = torch.min(target_q1,target_q2)
            y_expected = br + self.gamma * target_q    
        y_predicted1, y_predicted2 = self.critic.forward([bs,ba]) 
        errors = y_expected - y_predicted1

        ## update the critic
        critic_loss = nn.MSELoss()
        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)
        self.critic_optimizers.zero_grad()
        loss_critic.backward()
        self.critic_optimizers.step()
        
        ## update the actor
        if self.itera % self.policy_freq == 0:
            ## distinguish the intervention steps and non-intervention steps, and their corresponded variables
            index1,_ = np.where(bi==0)
            index2,_ = np.where(bi==1)
            bs1,_,_,_=bs[index1],ba[index1],br[index1],bs_[index1]
            bs2,ba2,_,_=bs[index2],ba[index2],br[index2],bs_[index2]
            
            ## if there exists human intervention steps
            if bs2.size(0) != 0:
                # if there exists non-intervention steps
                if bs1.size(0) != 0:
                    bs1 = torch.reshape(bs1,(len(bs1), self.state_dim_height, self.state_dim_width))
                    bs2 = torch.reshape(bs2,(len(bs2), self.state_dim_height, self.state_dim_width))
                    pred_a1 = self.actor.forward(bs1)
                    pred_a2 = self.actor.forward(bs2)
                    # calculate the TD3 loss
                    loss_actor1 = (-self.critic.forward([bs1,pred_a1])[0])
                    
                    with torch.no_grad():
                        # calculate the Q advantage weights
                        weights = torch.exp( self.critic_target([bs2,ba2])[0] - self.critic_target([bs2,pred_a2])[0])
                        weights[weights < 1] = 1
                        weights = weights - 1

                        # calculate the final weights
                        delay = 0.997 ** epoch # soft update coefficient
                        weights = delay * 3 + (1-delay) * (weights) * 3
                    
                    # calculate the human-guidance loss
                    lam = 0.997 ** epoch # episodic fading factor
                    loss_actor2 = lam * weights * ((pred_a2 - ba2)**2)

                    # calculate the final loss
                    loss_actor = torch.cat((loss_actor1,loss_actor2),0).mean()
                
                # if there are all intervention steps
                else:
                    pred_a = self.actor.forward(bs)
                    with torch.no_grad():
                        # calculate the Q advantage weights
                        weights = torch.exp( self.critic_target([bs,ba])[0] - self.critic_target([bs,pred_a])[0])
                        weights[weights > 1] = 1
                        weights = weights - 1

                        # calculate the final weights
                        delay = 0.997 ** epoch # soft update coefficient
                        weights = delay * 3 + (1-delay) * (weights) * 3
                    
                    # calculate the final loss
                    lam = 0.997 ** epoch # episodic fading factor
                    loss_actor = lam * weights * ((pred_a - ba)**2)
                    loss_actor = loss_actor.mean()
            
            ## if there does not exist human intervention steps
            else:
                pred_a = self.actor.forward(bs)
                # calculate the TD3 loss
                loss_actor = (-self.critic.forward([bs,pred_a])[0]).mean()
            
            self.actor_optimizer.zero_grad()
            loss_actor.backward()
            self.actor_optimizer.step()

            #soft replacement for target networks
            soft_update(self.actor_target,self.actor,self.tau)
            soft_update(self.critic_target,self.critic,self.tau)

            loss_a = loss_actor.mean().item()

        loss_c = loss_critic.mean().item()
        
        self.itera += 1

        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()) )
        
        return loss_c, loss_a


    ## pre-initialization trick, train the critic before the formal learning process of DRL
    def pre_init_critic(self, batch_size=BATCH_SIZE):
        
        ## batched state, batched action, batched action from expert, batched intervention signal, batched reward, batched next state
        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(self.batch_size)
        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        ba = torch.tensor(ba, dtype=torch.float).to(self.device)
        ba_e = torch.tensor(ba_e, dtype=torch.float).to(self.device)
        br = torch.tensor(br, dtype=torch.float).to(self.device)
        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        
        ## calculate the predicted values of the critic
        with torch.no_grad():
            noise = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)
            a_ = (self.actor_target(bs_).detach() + noise).clamp(0, 1)
            target_q1, target_q2 = self.critic_target([bs_,a_])
            target_q1 = target_q1.detach()
            target_q2 = target_q2.detach()
            target_q = torch.min(target_q1,target_q2)
            y_expected = br + self.gamma * target_q   
        y_predicted1, y_predicted2 = self.critic.forward([bs,ba])  
        errors = y_expected - y_predicted1

        ## update the critic
        critic_loss = nn.MSELoss()
        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)
        self.critic_optimizers.zero_grad()
        loss_critic.backward()
        self.critic_optimizers.step()

        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()))

    ## pre-initialization trick, train the actor before the formal learning process of DRL
    def pre_init_actor(self, batch_size=BATCH_SIZE):
        
        ## batched state, batched action
        bs, ba, _, _, _ , _= self.retrive(self.batch_size)
        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        ba = torch.tensor(ba, dtype=torch.float).to(self.device)

        pred_a = self.actor.forward(bs)
        
        # calculate the supervised learning loss
        loss_actor = ((pred_a - ba)**2).mean()

        # update the actor
        self.actor_optimizer.zero_grad()
        loss_actor.backward()
        self.actor_optimizer.step()
        

    def choose_action(self,state):
        state = torch.tensor(state, dtype=torch.float).reshape(self.state_dim_height, self.state_dim_width).to(self.device)
        state = state.unsqueeze(0)
        
        action = self.actor.forward(state).detach()
        action = action.squeeze(0).cpu().numpy()
        action = np.clip(action,-1,1)

        return action
    

    def store_transition(self, s, a, a_e, i, r, s_):

        ## state, action, action from expert, intervention signal, reward, next state
        transition = np.hstack((s, a, a_e, i, r, s_)) 
        self.memory.store(transition)
        self.pointer += 1
    

    def retrive(self, batch_size):

        tree_index, bt, ISWeight = self.memory.sample(batch_size)
        bs = bt[:, :self.state_dim]
        ba = bt[:, self.state_dim: self.state_dim + self.action_dim]
        ba_e = bt[:, self.state_dim + self.action_dim: self.state_dim + self.action_dim + self.action_dim]
        bi = bt[:, -self.state_dim - 2: -self.state_dim - 1]
        br = bt[:, -self.state_dim - 1: -self.state_dim]
        bs_ = bt[:, -self.state_dim:]
        ## batched state, batched action, batched action from expert, batched intervention signal, batched reward, batched next state
        return bs, ba, ba_e, bi, br, bs_, tree_index, ISWeight
    

    def memory_save(self):
        
        per = open("memory.pkl", 'wb')
        str = pickle.dumps(self.memory)
        per.write(str)
        per.close()
    

    def memory_load(self):
        
        with open("memory.pkl",'rb') as file:
            self.memory  = pickle.loads(file.read())
    

    def load_model(self, output):
        if output is None: return
        self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(output)))
        self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(output)))


    def save_model(self, output):
        torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(output))
        torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(output))
        

    def save(self, log_dir, epoch):
        state = {'actor':self.actor.state_dict(), 'actor_target':self.actor_target.state_dict(),
                 'actor_optimizer':self.actor_optimizer.state_dict(), 
                 'critic':self.critic.state_dict(), 'critic_target':self.critic_target.state_dict(),
                 'critic_optimizers':self.critic_optimizers.state_dict(),
                 'epoch':epoch}
        torch.save(state, log_dir)
    

    def load(self, log_dir):
        checkpoint = torch.load(log_dir)
        self.actor.load_state_dict(checkpoint['actor'])
        self.actor_target.load_state_dict(checkpoint['actor_target'])
        self.actor_optimizer.load_state_dict(checkpoint['actor_optimizer'])
        self.critic.load_state_dict(checkpoint['critic'])
        self.critic_target.load_state_dict(checkpoint['critic_target'])
        self.critic_optimizers.load_state_dict(checkpoint['critic_optimizers'])


!!! TD3IARL.py !!!

'''
This algorithm is a IA-RL implementation on off-policy TD3 algorithm, to check the original IA-RL algorithm
you can refer to https://arxiv.org/abs/1811.06187.
Since it is a baseline algorithm, the descriptions are mostly omitted, please visit the HUGTD3.py for more implementation details
'''

import pickle
import numpy as np

import torch
import torch.nn as nn

from TD3_based_DRL.priority_replay import Memory
from TD3_based_DRL.network_model import Actor,Critic
from TD3_based_DRL.util import hard_update, soft_update

seed = 2
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

MEMORY_CAPACITY = 38400
BATCH_SIZE = 128
GAMMA = 0.95
LR_C = 0.0005
LR_A = 0.0002
LR_I = 0.01
TAU = 0.001
POLICY_NOSIE = 0.2
POLICY_FREQ = 1
NOISE_CLIP = 0.5

class DRL:
        
    def __init__(self, action_dim, state_dim, LR_C = LR_C, LR_A = LR_A):

        self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
        
        self.state_dim = state_dim[0] * state_dim[1]
        self.state_dim_width = state_dim[0]
        self.state_dim_height = state_dim[1]
        self.action_dim = action_dim
        self.batch_size = BATCH_SIZE
        self.gamma = GAMMA
        self.tau = TAU
        self.policy_noise = POLICY_NOSIE
        self.noise_clip = NOISE_CLIP
        self.policy_freq = POLICY_FREQ
        self.itera = 0

        self.pointer = 0
        self.memory = Memory(MEMORY_CAPACITY)
        
        self.actor = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_target = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),LR_A)
        
        self.critic = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_target = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_optimizers = torch.optim.Adam(self.critic.parameters(),LR_C)
        
        hard_update(self.actor_target,self.actor)
        hard_update(self.critic_target,self.critic)
        
            
    def learn(self, batch_size = BATCH_SIZE, epoch=0):

        ## batched state, batched action, batched action from expert, batched intervention signal, batched reward, batched next state
        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(batch_size)
        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        ba = torch.tensor(ba, dtype=torch.float).to(self.device).to(self.device)
        ba_e = torch.tensor(ba_e, dtype=torch.float).to(self.device).to(self.device)
        br = torch.tensor(br, dtype=torch.float).to(self.device).to(self.device)
        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)

        # initialize the loss variables
        loss_c, loss_a = 0, 0

        ## calculate the predicted values of the critic
        with torch.no_grad():
            noise1 = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)
            a_ = (self.actor_target(bs_).detach() + noise1).clamp(0, 1)
            target_q1, target_q2 = self.critic_target([bs_,a_])
            target_q1 = target_q1.detach()
            target_q2 = target_q2.detach()
            target_q = torch.min(target_q1,target_q2)
            y_expected = br + self.gamma * target_q    
        y_predicted1, y_predicted2 = self.critic.forward([bs,ba]) 
        errors = y_expected - y_predicted1
        
        ## update the critic
        critic_loss = nn.MSELoss()
        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)
        self.critic_optimizers.zero_grad()
        loss_critic.backward()
        self.critic_optimizers.step()

        ## update the actor
        if self.itera % self.policy_freq == 0:

            index1,_ = np.where(bi==0)
            index2,_ = np.where(bi==1)
            bs1,_,_,_=bs[index1],ba[index1],br[index1],bs_[index1]
            bs2,ba2,_,_=bs[index2],ba[index2],br[index2],bs_[index2]
        
            if bs2.size(0) != 0:
                if bs1.size(0) != 0:
                    bs1 = torch.reshape(bs1,(len(bs1), self.state_dim_height, self.state_dim_width))
                    bs2 = torch.reshape(bs2,(len(bs2), self.state_dim_height, self.state_dim_width))
                    pred_a1 = self.actor.forward(bs1)
                    pred_a2 = self.actor.forward(bs2)
                    loss_actor1 = (-self.critic.forward([bs1,pred_a1])[0])
                    ## fixed weight for human guidance actions
                    loss_actor2 = 3 * ((pred_a2 - ba2)**2)
                    loss_actor = torch.cat((loss_actor1,loss_actor2),0).mean()
                else:
                    pred_a = self.actor.forward(bs)
                    loss_actor = 3*((pred_a - ba)**2)
                    loss_actor = loss_actor.mean()
            else:
                pred_a = self.actor.forward(bs)
                loss_actor = (-self.critic.forward([bs,pred_a])[0]).mean()
            
            self.actor_optimizer.zero_grad()
            loss_actor.backward()
            self.actor_optimizer.step()

            soft_update(self.actor_target,self.actor,self.tau)
            soft_update(self.critic_target,self.critic,self.tau)

            loss_a = loss_actor.mean().item()

        loss_c = loss_critic.mean().item()
        
        self.itera += 1

        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()) )

        return loss_c, loss_a
    
                
    def choose_action(self,state):

        state = torch.tensor(state,dtype=torch.float).reshape(self.state_dim_height, self.state_dim_width).to(self.device)
        state = state.unsqueeze(0)
        
        action = self.actor.forward(state).detach()
        action = action.squeeze(0).cpu().numpy()
        action = np.clip(action,-1, 1)

        return action
    

    def store_transition(self, s, a, a_e, i, r, s_):
        transition = np.hstack((s, a, a_e, i, r, s_)) 
        self.memory.store(transition)
        self.pointer += 1
    

    def retrive(self, batch_size):
        tree_index, bt, ISWeight = self.memory.sample(batch_size) 
        bs = bt[:, :self.state_dim]
        ba = bt[:, self.state_dim: self.state_dim + self.action_dim]
        ba_e = bt[:, self.state_dim + self.action_dim: self.state_dim + self.action_dim + self.action_dim]
        bi = bt[:, -self.state_dim - 2: -self.state_dim - 1]
        br = bt[:, -self.state_dim - 1: -self.state_dim]
        bs_ = bt[:, -self.state_dim:]
        
        return bs, ba, ba_e, bi, br, bs_, tree_index, ISWeight
    

    def memory_save(self):
        
        per = open("memory_IARL.pkl", 'wb')
        str = pickle.dumps(self.memory)
        per.write(str)
        per.close()
    

    def memory_load(self):
        
        with open("memory_IARL.pkl",'rb') as file:
            self.memory  = pickle.loads(file.read())
        
    
    def load_model(self, output):
        if output is None: return
        self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(output)))
        self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(output)))

    def save_model(self, output):
        torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(output))
        torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(output))
        
    def save(self, log_dir, epoch):
        state = {'actor':self.actor.state_dict(), 'actor_target':self.actor_target.state_dict(),
                 'actor_optimizer':self.actor_optimizer.state_dict(), 
                 'critic':self.critic.state_dict(), 'critic_target':self.critic_target.state_dict(),
                 'critic_optimizers':self.critic_optimizers.state_dict(),
                 'epoch':epoch}
        torch.save(state, log_dir)
        

    def load(self, log_dir):
        checkpoint = torch.load(log_dir)
        self.actor.load_state_dict(checkpoint['actor'])
        self.actor_target.load_state_dict(checkpoint['actor_target'])
        self.actor_optimizer.load_state_dict(checkpoint['actor_optimizer'])
        self.critic.load_state_dict(checkpoint['critic'])
        self.critic_target.load_state_dict(checkpoint['critic_target'])
        self.critic_optimizers.load_state_dict(checkpoint['critic_optimizers'])


!!! TD3HIRL.py !!!

'''
This algorithm is a HI-RL implementation based on an off-policy TD3 algorithm.
To check the original HI-RL algorithm (based on DDQN), you can refer to https://arxiv.org/abs/1707.05173.
Since TD3HI is a baseline algorithm, the annotations are mostly omitted, please visit the HUGTD3.py for more details.
'''
import pickle
import numpy as np

import torch
import torch.nn as nn

from TD3_based_DRL.priority_replay import Memory
from TD3_based_DRL.network_model import Actor,Critic
from TD3_based_DRL.util import hard_update, soft_update

seed = 2
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

MEMORY_CAPACITY = 38400
BATCH_SIZE = 128
GAMMA = 0.95
LR_C = 0.0005
LR_A = 0.0002
LR_I = 0.01
TAU = 0.001
POLICY_NOSIE = 0.2
POLICY_FREQ = 1
NOISE_CLIP = 0.5

class DRL:
        
    def __init__(self,action_dim,state_dim, LR_C = LR_C, LR_A = LR_A):
        self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
        
        self.state_dim = state_dim[0] * state_dim[1]
        self.state_dim_width = state_dim[0]
        self.state_dim_height = state_dim[1]
        self.action_dim = action_dim
        self.batch_size = BATCH_SIZE
        self.gamma = GAMMA
        self.tau = TAU
        self.policy_noise = POLICY_NOSIE
        self.noise_clip = NOISE_CLIP
        self.policy_freq = POLICY_FREQ
        self.itera = 0

        self.pointer = 0
        self.memory = Memory(MEMORY_CAPACITY)
        
        self.actor = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_target = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),LR_A)
        
        self.critic = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_target = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_optimizers = torch.optim.Adam(self.critic.parameters(),LR_C)
        
        hard_update(self.actor_target,self.actor)
        hard_update(self.critic_target,self.critic)

            
    def learn(self, batch_size=BATCH_SIZE, epoch=0):

        ## batched state, batched action, batched action from expert, batched intervention signal, batched reward, batched next state
        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(batch_size)
        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        ba = torch.tensor(ba, dtype=torch.float).to(self.device)
        ba_e = torch.tensor(ba_e, dtype=torch.float).to(self.device)
        br = torch.tensor(br, dtype=torch.float).to(self.device)
        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        
        # initialize the loss variables
        loss_c, loss_a = 0, 0

        ## calculate the predicted values of the critic
        with torch.no_grad():
            noise = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)
            a_ = (self.actor_target(bs_).detach() + noise).clamp(0, 1)
            target_q1, target_q2 = self.critic_target([bs_,a_])
            target_q1 = target_q1.detach()
            target_q2 = target_q2.detach()
            target_q = torch.min(target_q1,target_q2)
            y_expected = br + self.gamma * target_q   
        y_predicted1, y_predicted2 = self.critic.forward([bs,ba])    
        errors = y_expected - y_predicted1
        
        ## update the critic
        critic_loss = nn.MSELoss()
        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)
        self.critic_optimizers.zero_grad()
        loss_critic.backward()
        self.critic_optimizers.step()
        
        ## update the actor
        if self.itera % self.policy_freq == 0:

            pred_a = self.actor.forward(bs)
            loss_actor = (-self.critic.forward([bs,pred_a])[0])

            self.actor_optimizer.zero_grad()
            loss_actor.mean().backward()
            self.actor_optimizer.step()

            soft_update(self.actor_target,self.actor,self.tau)
            soft_update(self.critic_target,self.critic,self.tau)

            loss_a = loss_actor.mean().item()

        loss_c = loss_critic.mean().item()

        self.itera += 1

        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()) )
        
        return loss_c, loss_a
    
                
    def choose_action(self,state):

        state = torch.tensor(state,dtype=torch.float).reshape(self.state_dim_height, self.state_dim_width).to(self.device)
        state = state.unsqueeze(0)
        
        action = self.actor.forward(state).detach()
        action = action.squeeze(0).cpu().numpy()
        action = np.clip(action,-1, 1)

        return action
    

    def store_transition(self, s, a, a_e, i, r, s_):

        transition = np.hstack((s, a, a_e, i, r, s_))  
        self.memory.store(transition)
        self.pointer += 1
    

    def retrive(self, batch_size):

        tree_index, bt, ISWeight = self.memory.sample(batch_size)   
        bs = bt[:, :self.state_dim]
        ba = bt[:, self.state_dim: self.state_dim + self.action_dim]
        ba_e = bt[:, self.state_dim + self.action_dim: self.state_dim + self.action_dim + self.action_dim]
        bi = bt[:, -self.state_dim - 2: -self.state_dim - 1]
        br = bt[:, -self.state_dim - 1: -self.state_dim]
        bs_ = bt[:, -self.state_dim:]
        
        return bs, ba, ba_e, bi, br, bs_, tree_index, ISWeight
    

    def memory_save(self):
        
        per = open("memory.pkl", 'wb')
        str = pickle.dumps(self.memory)
        per.write(str)
        per.close()
    

    def memory_load(self):
        
        with open("memory.pkl",'rb') as file:
            self.memory  = pickle.loads(file.read())
            

    def load_model(self, output):
        if output is None: return
        self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(output)))
        self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(output)))


    def save_model(self, output):
        torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(output))
        torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(output))
        

    def save(self, log_dir, epoch):
        state = {'actor':self.actor.state_dict(), 'actor_target':self.actor_target.state_dict(),
                 'actor_optimizer':self.actor_optimizer.state_dict(), 
                 'critic':self.critic.state_dict(), 'critic_target':self.critic_target.state_dict(),
                 'critic_optimizers':self.critic_optimizers.state_dict(),
                 'epoch':epoch}
        torch.save(state, log_dir)
        

    def load(self, log_dir):
        checkpoint = torch.load(log_dir)
        self.actor.load_state_dict(checkpoint['actor'])
        self.actor_target.load_state_dict(checkpoint['actor_target'])
        self.actor_optimizer.load_state_dict(checkpoint['actor_optimizer'])
        self.critic.load_state_dict(checkpoint['critic'])
        self.critic_target.load_state_dict(checkpoint['critic_target'])
        self.critic_optimizers.load_state_dict(checkpoint['critic_optimizers'])


!!! TD3.py !!!

'''
This algorithm is a standard TD3 algorithm. 
Original paper: https://arxiv.org/abs/1802.09477.
'''
import pickle
import numpy as np

import torch
import torch.nn as nn

from TD3_based_DRL.priority_replay import Memory
from TD3_based_DRL.network_model import Actor,Critic
from TD3_based_DRL.util import hard_update, soft_update

seed = 2
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

MEMORY_CAPACITY = 38400
BATCH_SIZE = 128
GAMMA = 0.95
LR_C = 0.0005
LR_A = 0.0002
LR_I = 0.01
TAU = 0.001
POLICY_NOSIE = 0.2
POLICY_FREQ = 1
NOISE_CLIP = 0.5

class DRL:
        
    def __init__(self,action_dim,state_dim, LR_C = LR_C, LR_A = LR_A):
        self.use_cuda = True
        
        self.state_dim = state_dim[0] * state_dim[1]
        self.state_dim_width = state_dim[0]
        self.state_dim_height = state_dim[1]
        self.action_dim = action_dim
        self.batch_size = BATCH_SIZE
        self.gamma = GAMMA
        self.tau = TAU
        self.policy_noise = POLICY_NOSIE
        self.noise_clip = NOISE_CLIP
        self.policy_freq = POLICY_FREQ
        self.itera = 0

        self.pointer = 0
        self.memory = Memory(MEMORY_CAPACITY)
        
        self.actor = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_target = Actor(self.state_dim,self.action_dim).to(self.device)
        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),LR_A)
        
        self.critic = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_target = Critic(self.state_dim,self.action_dim).to(self.device)
        self.critic_optimizers = torch.optim.Adam(self.critic.parameters(),LR_C)
        
        hard_update(self.actor_target,self.actor)
        hard_update(self.critic_target,self.critic)

            
    def learn(self, batch_size=BATCH_SIZE, epoch=0):

        ## batched state, batched action, batched reward, batched next state
        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(batch_size)
        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        ba = torch.tensor(ba, dtype=torch.float).to(self.device)
        br = torch.tensor(br, dtype=torch.float).to(self.device)
        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)
        
        # initialize the loss variables
        loss_c, loss_a = 0, 0

        ## calculate the predicted values of the critic
        with torch.no_grad():
            noise = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)
            a_ = (self.actor_target(bs_).detach() + noise).clamp(0, 1)
            target_q1, target_q2 = self.critic_target([bs_,a_])
            target_q1 = target_q1.detach()
            target_q2 = target_q2.detach()
            target_q = torch.min(target_q1,target_q2)
            y_expected = br + self.gamma * target_q   
        y_predicted1, y_predicted2 = self.critic.forward([bs,ba])    
        
        ## update the critic
        critic_loss = nn.MSELoss()
        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)
        self.critic_optimizers.zero_grad()
        loss_critic.backward()
        self.critic_optimizers.step()
        
        ## update the actor
        if self.itera % self.policy_freq == 0:

            pred_a = self.actor.forward(bs)
            loss_actor = (-self.critic.forward([bs,pred_a])[0])

            self.actor_optimizer.zero_grad()
            loss_actor.mean().backward()
            self.actor_optimizer.step()

            soft_update(self.actor_target,self.actor,self.tau)
            soft_update(self.critic_target,self.critic,self.tau)

            loss_a = loss_actor.mean().item()

        loss_c = loss_critic.mean().item()

        self.itera += 1

        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()) )

        return loss_c, loss_a
    
                
    def choose_action(self,state):

        state = torch.tensor(state,dtype=torch.float).reshape(self.state_dim_height, self.state_dim_width).to(self.device)
        state = state.unsqueeze(0)
        
        action = self.actor.forward(state).detach()
        action = action.squeeze(0).cpu().numpy()
        action = np.clip(action,-1, 1)

        return action
    
    
    '''
    To conveniently implement all the algorithms in the same training script, the memory buffer here
    keeps the same shape as other human-guidance DRL algorithms. However, in this vanilla TD3 algorithm,
    the human-guidance-related indicators, i.e., action from the human expert, and the intervention signal, 
    are not available in fact.
    '''
    def store_transition(self, s, a, a_e, i, r, s_):

        transition = np.hstack((s, a, a_e, i, r, s_))  
        self.memory.store(transition)
        self.pointer += 1
    

    def retrive(self, batch_size):

        tree_index, bt, ISWeight = self.memory.sample(batch_size)   
        bs = bt[:, :self.state_dim]
        ba = bt[:, self.state_dim: self.state_dim + self.action_dim]
        ba_e = bt[:, self.state_dim + self.action_dim: self.state_dim + self.action_dim + self.action_dim]
        bi = bt[:, -self.state_dim - 2: -self.state_dim - 1]
        br = bt[:, -self.state_dim - 1: -self.state_dim]
        bs_ = bt[:, -self.state_dim:]
        
        return bs, ba, ba_e, bi, br, bs_, tree_index, ISWeight
    

    def memory_save(self):
        
        per = open("memory.pkl", 'wb')
        str = pickle.dumps(self.memory)
        per.write(str)
        per.close()
    

    def memory_load(self):
        
        with open("memory.pkl",'rb') as file:
            self.memory  = pickle.loads(file.read())
            

    def load_model(self, output):
        if output is None: return
        self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(output)))
        self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(output)))


    def save_model(self, output):
        torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(output))
        torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(output))
        

    def save(self, log_dir, epoch):
        state = {'actor':self.actor.state_dict(), 'actor_target':self.actor_target.state_dict(),
                 'actor_optimizer':self.actor_optimizer.state_dict(), 
                 'critic':self.critic.state_dict(), 'critic_target':self.critic_target.state_dict(),
                 'critic_optimizers':self.critic_optimizers.state_dict(),
                 'epoch':epoch}
        torch.save(state, log_dir)
        

    def load(self, log_dir):
        checkpoint = torch.load(log_dir)
        self.actor.load_state_dict(checkpoint['actor'])
        self.actor_target.load_state_dict(checkpoint['actor_target'])
        self.actor_optimizer.load_state_dict(checkpoint['actor_optimizer'])
        self.critic.load_state_dict(checkpoint['critic'])
        self.critic_target.load_state_dict(checkpoint['critic_target'])
        self.critic_optimizers.load_state_dict(checkpoint['critic_optimizers'])
